package com.yuanfeng.controller;

import com.yuanfeng.basedata.annotation.ConfigManagementSwagger;
import com.yuanfeng.basedata.api.FineFoodConstantApi;
import com.yuanfeng.basedata.entiry.KcsjUser;
import com.yuanfeng.basedata.response.ResponseResult;
import com.yuanfeng.basedata.utils.AesEncryptUtil;
import com.yuanfeng.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName UserController
 * @Description T0D0
 * @Author yuanfeng
 * @Date 2019/9/6 16:33
 * @Version 1.0
 **/

@RequestMapping(FineFoodConstantApi.FOREHEAD_PATH+"/user")
@RestController
@Validated
@Api(description = "用户注册登陆模块")
@ConfigManagementSwagger
public class UserLoginRegController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginRegController.class);

    @Value("${aes_key}")
    private String aesKey;
    @Value("${aes_iv}")
    private String aesIv;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户登陆接口")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseResult<KcsjUser> userLogin(@ApiParam("登陆用户") @RequestBody KcsjUser kcsjUser, @ApiParam("Http请求对象") HttpServletRequest request){
        ResponseResult<KcsjUser> responseResult = new ResponseResult<>();
        try {
            //得到用户名密码
            String userName = kcsjUser.getUserName();
            String userPassword = AesEncryptUtil.encrypt(kcsjUser.getUserPassword(), aesKey, aesIv).trim();

            if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPassword)){

                LOGGER.warn("用户名或者密码为空!");
                responseResult.setCode(500);
                responseResult.setMessage("用户名或者密码为空");
                responseResult.setData(null);
                return responseResult;
            }

            //存在用户名密码
            KcsjUser oneKcsjUser = userService.getOneKcsjUser(userName, userPassword);
            if(!Objects.isNull(oneKcsjUser)){
                responseResult.setCode(200);
                responseResult.setMessage("登陆成功");
                responseResult.setData(oneKcsjUser);
            }else{
                responseResult.setCode(200);
                responseResult.setMessage("用户名或密码错误");
                responseResult.setData(oneKcsjUser);
            }

        } catch (Exception e) {
            LOGGER.error(e+"");
            responseResult.setCode(500);
            responseResult.setMessage("登陆失败");
            responseResult.setData(null);
        }
        return responseResult;
    }
    @ApiOperation(value = "用户注册接口")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ResponseResult<Map> userRegister(@ApiParam("注册用户") @RequestBody KcsjUser kcsjUser){
        ResponseResult<Map> responseResult = new ResponseResult<>();
        try {

            String password = AesEncryptUtil.encrypt(kcsjUser.getUserPassword(), aesKey, aesIv).trim();
            kcsjUser.setUserPassword(password);
            KcsjUser registerUser = userService.registerUser(kcsjUser);

            //新增成功后不为空
            if(Objects.nonNull(registerUser)){
                Map resultMap = new HashMap<String,Object>();
                resultMap.put("result",registerUser);
                responseResult.setCode(200);
                responseResult.setMessage("注册成功");
                responseResult.setData(resultMap);
            }

        } catch (Exception e) {
            LOGGER.error(e+"");
            responseResult.setCode(500);
            responseResult.setMessage("注册失败");
            responseResult.setData(null);
        }
        return responseResult;
    }
    @ApiOperation(value = "用户信息修改")
    @RequestMapping(value = "/update/user_info",method = RequestMethod.PUT)
    public ResponseResult<KcsjUser> userInfoUpdate(@ApiParam("修改用户") @RequestBody KcsjUser kcsjUser ,@ApiParam("用户ID") @RequestParam Integer userId){
        ResponseResult<KcsjUser> responseResult = new ResponseResult<>();
        try {

            Optional<KcsjUser> oneUser = userService.findOneUser(userId);
            //有该用户
            if(oneUser.isPresent() && Objects.nonNull(kcsjUser)){
                //获取实例对象
                int affectRows = userService.updateByUserId(kcsjUser.getUserName(),
                        kcsjUser.getUserPassword(),
                        kcsjUser.getUserEmail(),
                        kcsjUser.getUserBirthday(),
                        kcsjUser.getUserAddress(),
                        userId);
                LOGGER.info("影响了"+affectRows+"行");
                responseResult.setCode(200);
                responseResult.setMessage("更新成功！");
                responseResult.setData(kcsjUser);
            }
            else {
                LOGGER.error("查无此人");
                responseResult.setCode(500);
                responseResult.setMessage("没有该用户，更新失败！");
                responseResult.setData(null);
            }

        } catch (Exception e) {
            LOGGER.error(e+"");
            responseResult.setCode(500);
            responseResult.setMessage("更新失败");
            responseResult.setData(null);
        }
        return responseResult;
    }

}
